package com.ooqiu.gaming.ui.channel;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.api.entities.CateRes;
import com.ooqiu.gaming.base.BaseActivity;
import com.ooqiu.gaming.common.Constants;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.db.Channel;
import com.ooqiu.gaming.utils.LocalBroadcastManagerUtil;
import com.ooqiu.gaming.view.Topbar;
import com.ooqiu.greendao.ChannelDao;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

@Route(path = EditChannelActivity.PATH)
public class EditChannelActivity extends BaseActivity {
    public static final String PATH = "/gn/edit_channel";
    @BindView(R.id.top_bar)
    Topbar mTopBar;
    @BindView(R.id.rv_channel)
    RecyclerView mRvChannel;
    private ChannelAdapter adapter;


    GamingApi mGamingApi;
    final List<Channel> enableItems = new ArrayList<>();
    final List<Channel> disableItems = new ArrayList<>();

    //    List<Channel> MineItem = new ArrayList<>();
    ChannelDao mChannelDao;
    @Autowired(name = "action")
    String action;


    UserStorage mUserStorage;
    @Override
    public int initContentView() {
        return R.layout.activity_edit_channel;
    }

    @Override
    public void initInjector() {
        ButterKnife.bind(this);
        getRouter().inject(this);
        mGamingApi = getApplicationComponent().getGamingApi();
        mChannelDao = getApplicationComponent().getDaoSession().getChannelDao();
        mUserStorage = getApplicationComponent().getUserStorage();
    }

    @Override
    public void initUiAndListener() {
        initData();

        if (action.equals(Constants.ACTION_INDEX_CATE_CHANGE)) {
            fetchCate();
        } else {
            fetchVideoCate();
        }
        mTopBar.setOnMenuClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected Toolbar toolbarIdRes() {
        return mTopBar;
    }

    @Override
    protected View statusLayoutId() {
        return null;
    }

    @Override
    protected void onStop() {
        super.onStop();
//        onSaveData();
    }


    private void initData() {

        GridLayoutManager manager = new GridLayoutManager(this, 4);
        mRvChannel.setLayoutManager(manager);

        ItemDragHelperCallback callback = new ItemDragHelperCallback();
        final ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(mRvChannel);

        adapter = new ChannelAdapter(this, helper, enableItems, disableItems);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int viewType = adapter.getItemViewType(position);
                return viewType == ChannelAdapter.TYPE_MY || viewType == ChannelAdapter.TYPE_OTHER ? 1 : 4;
            }
        });
        mRvChannel.setAdapter(adapter);

        adapter.setOnMyChannelItemClickListener(new ChannelAdapter.OnMyChannelItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {

            }
        });

    }

    public void onSaveData() {

        Observable
                .create(new ObservableOnSubscribe<Boolean>() {
                    @Override
                    public void subscribe(@NonNull ObservableEmitter<Boolean> e) throws Exception {

//                        List<Channel> oldItems = dao.query(Constant.NEWS_CHANNEL_ENABLE);
//                        e.onNext(!compare(oldItems, adapter.getmMyChannelItems()));
                    }
                })
                .subscribeOn(Schedulers.io())
                .doOnNext(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
//                        if (aBoolean) {
//                            List<Channel> enableItems = adapter.getmMyChannelItems();
//                            List<Channel> disableItems = adapter.getmOtherChannelItems();
//                            dao.removeAll();
//                            for (int i = 0; i < enableItems.size(); i++) {
//                                NewsChannelBean bean = enableItems.get(i);
//                                dao.add(bean.getChannelId(), bean.getChannelName(), Constant.NEWS_CHANNEL_ENABLE, i);
//                            }
//                            for (int i = 0; i < disableItems.size(); i++) {
//                                NewsChannelBean bean = disableItems.get(i);
//                                dao.add(bean.getChannelId(), bean.getChannelName(), Constant.NEWS_CHANNEL_DISABLE, i);
//                            }
//                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean isRefresh) throws Exception {
//                        RxBus.getInstance().post(NewsTabLayout.TAG, isRefresh);
                    }
                });
    }

    public synchronized <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if (a.size() != b.size())
            return false;
//        Collections.sort(a);
//        Collections.sort(b);
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i)))
                return false;
        }
        return true;
    }


    private void fetchCate() {
        mGamingApi.fetchNewsCate()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<CateRes>() {
                    @Override
                    public void onNext(CateRes cateRes) {
                        if (!mUserStorage.isLogin()) {
                            enableItems.addAll(mChannelDao.queryBuilder().where(ChannelDao.Properties.Modoule_id.eq(Channel.MODULE_ID_INDEX),ChannelDao.Properties.Show.eq(true)).build().list());
                            List<Channel> mTempChannel = new ArrayList<>();
                            mTempChannel.addAll(cateRes.getSystem());
                            for (Channel channel : cateRes.getSystem()) {
                                for (Channel enableItem : enableItems) {
                                    if (enableItem.getReal_id().equals(channel.getCat_id())) {
                                        mTempChannel.remove(channel);
                                    }
                                }
                            }
                            disableItems.addAll(mTempChannel);
                        } else {
                            enableItems.addAll(cateRes.getMine());
                            disableItems.addAll(cateRes.getSystem());
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void fetchVideoCate() {
        mGamingApi.fetchVideoCate()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<CateRes>() {
                    @Override
                    public void onNext(CateRes cateRes) {
                        if (!mUserStorage.isLogin()) {
                            enableItems.addAll(mChannelDao.queryBuilder().where(ChannelDao.Properties.Modoule_id.eq(Channel.MODULE_ID_VIDEO),ChannelDao.Properties.Show.eq(true)).build().list());
                            List<Channel> mTempChannel = new ArrayList<>();
                            mTempChannel.addAll(cateRes.getSystem());
                            for (Channel channel : cateRes.getSystem()) {
                                for (Channel enableItem : enableItems) {
                                    if (enableItem.getReal_id().equals(channel.getCat_id())) {
                                        mTempChannel.remove(channel);
                                    }
                                }
                            }
                            disableItems.addAll(mTempChannel);
                        } else {
                            enableItems.addAll(cateRes.getMine());
                            disableItems.addAll(cateRes.getSystem());
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void save() {
        if (action.equals(Constants.ACTION_INDEX_CATE_CHANGE)) {
            if (mUserStorage.isLogin()) {
                mGamingApi.saveArticleCate(adapter.getmMyChannelItems())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProgressSubscriber<String>(mContext) {
                            @Override
                            public void onNext(String s) {
                                LocalBroadcastManagerUtil.post(mContext, action);
                                finish();
                            }

                            @Override
                            public void onFinish() {

                            }
                        });


            } else {
                mChannelDao.deleteInTx(mChannelDao.queryBuilder().where(ChannelDao.Properties.Modoule_id.eq(Channel.MODULE_ID_INDEX)).build().list());
                for (Channel channel : adapter.getmMyChannelItems()) {
                    channel.setModoule_id(Channel.MODULE_ID_INDEX);
                    channel.setShow(true);
                }

                mChannelDao.insertOrReplaceInTx(adapter.getmMyChannelItems());
                LocalBroadcastManagerUtil.post(mContext, action);
                finish();
            }
        } else {
            if (mUserStorage.isLogin()) {
                mGamingApi.saveVideoCate(adapter.getmMyChannelItems())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProgressSubscriber<String>(mContext) {
                            @Override
                            public void onNext(String s) {
                                LocalBroadcastManagerUtil.post(mContext, action);
                                finish();
                            }

                            @Override
                            public void onFinish() {

                            }
                        });
            }else {
                mChannelDao.deleteInTx(mChannelDao.queryBuilder().where(ChannelDao.Properties.Modoule_id.eq(Channel.MODULE_ID_VIDEO)).build().list());
                for (Channel channel : adapter.getmMyChannelItems()) {
                    channel.setModoule_id(Channel.MODULE_ID_VIDEO);
                    channel.setShow(true);
                }
                mChannelDao.insertOrReplaceInTx(adapter.getmMyChannelItems());
                LocalBroadcastManagerUtil.post(mContext, action);
                finish();
            }



        }


    }


}




